<template>
  <div class="wrap">

    <label-order-info-view
      :goods-data="goodsData"
      :data="data"
      :can-submit="true"
      :container-list="containerList"
      @submitGoods="checkGoodsNum"
      @getData="getData"
    ></label-order-info-view>

    <div class="mgt20" v-if="data.type !== 1">
      <el-button @click="jumpPage('labelOrderList')">{{ $t('common.back') }}</el-button>
      <export-button :func="getLabelOrderInfo" :query-params="this.id" v-if="false"></export-button>
      <el-button type="primary" @click="checkGoodsNum" v-if="data.status === 1" :loading="btnLoading">{{$t('labelOrder.确认已贴标')}}</el-button>
      <template v-if="data.type !== 1">
        <button-thermal :id="data.id" class="mgl10"></button-thermal>
      </template>
    </div>


  </div>
</template>

<script>
import {
  confirmLabelOrder,
  editLabelOrder,
  exportLabelGoodsLabelPdf, finishLabelOrder,
  getLabelOrderInfo,
  saveRlGoodsNum
} from "@/api/labelOrder";
import {deepCopy} from "@/utils";
import {jumpMiddleInfo, jumpPage, jumpShipmentInfo, jumpTransferInfo} from "@/utils/jumpView";
import LabelOrderInfoView from "@/views/labelOrder/components/LabelOrderInfoView.vue";
import ButtonThermal from "@/views/labelOrder/components/ButtonThermal.vue";
import ExportButton from "@/views/order/components/ExportButton.vue";

export default {
  name: "labelOrderInfo",
  components: {ExportButton, ButtonThermal, LabelOrderInfoView},
  data(){
    return {
      loading: false,
      data: {},
      goodsData: [],
      btnLoading: false,
      labelPdfDialog: false,
      labelPdfForm: {
        id: '',
        num: 0, // pdf数量
      },
      labelPdfLoading: false,
      containerId: 0, // 货柜的id
      containerList: [],
    }
  },
  created() {
    this.id = this.$route.query.id

    this.getData()
  },
  methods:{
    getLabelOrderInfo,
    jumpPage,
    jumpShipmentInfo,
    jumpTransferInfo,
    jumpMiddleInfo,
    getData(){
      this.loading = true
      getLabelOrderInfo(this.id)
        .then(res=>{
          this.loading = false
          if(res.error === 0){
            this.data = deepCopy(res.data)
            this.goodsData = []
            if(this.data.type !== 1){
              res.info.goodsData.forEach(item=>{
                item.sameToSuitIdLength = res.info.goodsData.filter(_item => _item.toSuitId === item.toSuitId).length
                if(item.sameToSuitIdLength === 1){
                  item.editExGoodsNum = item.totalExGoodsNum;
                }
                this.goodsData.push(item)
              })
            }else{
              this.goodsData = res.info.goodsData
            }
            this.containerList = res.info.containerList

          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    // 导出sku标
    showLabelPdf(row){
      this.labelPdfForm.id = row.id
      this.labelPdfForm.num = row.exGoodsNum
      this.labelPdfDialog = true
    },
    // 导出sku标
    exportLabelPdf(){
      this.labelPdfLoading = true
      const params = deepCopy(this.labelPdfForm)
      exportLabelGoodsLabelPdf(this.labelPdfForm)
        .then(res=>{
          this.labelPdfLoading = false
          this.labelPdfDialog = false
          const pdfFile = window.URL.createObjectURL(
            new Blob([res.data], { type: "application/pdf" })
          );
          if(this.data.status === 1){
            this.goodsData.some(item=>{
              if(item.id === params.id){
                item.rlGoodsNum = params.num
                return true
              }
            })
          }

          // 跳转页面预览
          window.open(pdfFile);
          // 60秒后释放
          setTimeout(()=>{
            URL.revokeObjectURL(pdfFile); //释放URL对象
          },60000)
        })
    },
    // 保存某条贴标数据
    saveRlGoodsNum(row){
      const data = {
        id: row.id,
        rlGoodsNum: row.rlOneStock + row.rlMiddleStock,
        rlOneStock: row.rlOneStock,
        rlMiddleStock: row.rlMiddleStock
      }
      saveRlGoodsNum(data)
        .then(res=>{
          // 成功不刷新数据
          if(res.error === 0){
            this.$successMessage(res.message)
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    checkGoodsNum(){
      new Promise((resolve, reject)=>{
        resolve()
      })
        .then(()=>{
          return new Promise((resolve, reject)=>{
            let flag = false
            if(this.data.type !== 1){
              this.goodsData.forEach(item=>{
                item.rlGoodsNum = item.rlOneStock + item.rlMiddleStock
              })
            }
            flag = this.goodsData.some(item=>{
              return item.rlGoodsNum !== item.exGoodsNum
            })
            if(flag){
              this.$warning(this.$t('labelOrder.实际贴标数据与预计贴标数量有差异，请先与客户沟通确认'),{
                'title': this.$t('labelOrder.确认贴标？'),
              })
                .then(()=>{
                  resolve()
                })
                .catch(()=>{
                  reject()
                })
            }else{
              resolve()
            }
          })
        })
        .then(()=>{
          this.finishLabelOrder()
        })
        .catch(()=>{

        })
    },
    // 确认已贴标
    finishLabelOrder(){
      if(this.data.type !== 1){
        this.goodsData.forEach(item=>{
          item.rlGoodsNum = item.rlOneStock + item.rlMiddleStock
        })
      }
      const data = {
        id: this.data.id,
        goodsData: this.goodsData
      }
      this.btnLoading = true
      finishLabelOrder(data)
        .then(res=>{
          this.btnLoading = false
          if(res.error === 0) {
            if(this.data.shipment){
              this.jumpShipmentInfo(this.data.shipment.id)
            }else if(this.data.middle){
              this.jumpMiddleInfo(this.data.middle.id)
            }else if(this.data.transfer){
              this.jumpTransferInfo(this.data.transfer.id)
            }else{
              this.getData()
            }

            this.$successMessage(res.message)
          } else {
            this.$errorMessage(res.message)
          }
        })
    },
    goShipment(id) {
      this.$router.push({
        name: 'shipmentInfo',
        query: {
          id: id
        }
      })
    },
    objectSpanMethod1({row, column, rowIndex, columnIndex}) {
      const mergeCell = this.mergeCell1()
      if (mergeCell[column.property]) {
        if (mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    mergeCell1(){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'totalExGoodsNum',
        'totalRlGoodsNum',
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      this.goodsData.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并
        if(item.fromSuitId && item.fromSuitId === this.goodsData[index - 1].fromSuitId){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    objectSpanMethod3({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.mergeCell3()
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    mergeCell3(){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'toGoodsId',
        'totalRlGoodsNum',
        'totalExGoodsNum'
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      this.goodsData.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并
        if(item.toSuitListId && item.toSuitListId === this.goodsData[index - 1].toSuitListId){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    //display: flex;
    //justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
  .header-card{
    font-size: 14px;
    background-color: rgba(242, 242, 242, 1);
    p{
      margin: 10px 0;
      padding: 0;
    }
    .font-bold{
      font-weight: bold;
    }
    .true-number{
      color: #FF0000;
      font-weight: 600;
    }
  }
}
.goods-table{
  .goods-title{
    font-size: 14px;
  }
  .goods-attr{
    font-size: 13px;
    color: #7F7F7F;
  }
}
.table-tips{

}

.header-card{
  position: relative;
  .button{
    position: absolute;
    display: flex;
    flex-direction: column;
    right: 20px;
    top: 30px;
  }
}
</style>
